import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import classNames from 'classnames'
import { Button, Input } from 'antd'
import IconFont from '@/components/IconFont'
import styles from './index.module.less'

const Icon = ({ type, active, onClick }) => {
  return (
    <div
      className={classNames(styles['icon-box'], { [styles.active]: active })}
      onClick={() => onClick(type)}
    >
      <IconFont
        type={type}
        className={classNames('icon-color-base', { [styles['icon-color']]: active })}
        style={{ fontSize: '24px' }}
      />
    </div>
  )
}

const Header = ({ value, onChange, onSave }) => {
  const navigate = useNavigate()
  const nameRef = useRef(null)
  const [active, setActive] = useState(true)
  const [show, setShow] = useState(false)

  useEffect(() => {
    if (show) {
      nameRef.current?.focus({
        cursor: 'end'
      })
    }
  }, [show])

  const onIconChange = (type) => {
    setActive(type === 'icon-set')
  }

  const onBack = () => {
    navigate('/dashboard')
  }

  return (
    <div className={styles.Header}>
      <div className={styles.left}>
        <Icon type="icon-over-back" onClick={onBack} />
        <div className={styles['opt-icon']}>
          <Icon type="icon-set" active={active} onClick={onIconChange} />
          <Icon type="icon-preview" active={!active} onClick={onIconChange} />
        </div>
      </div>
      <div className={styles.center}>
        {show ? (
          <Input ref={nameRef} value={value} onChange={onChange} onBlur={() => setShow(false)} />
        ) : (
          <>
            <span>新建仪表盘</span>
            <IconFont type="icon-edit" className="icon-color-base" onClick={() => setShow(true)} />
          </>
        )}
      </div>

      <Button type="primary" onClick={onSave}>
        保存
      </Button>
    </div>
  )
}

export default Header
